"use strict";
import { useState, useEffect, useRef } from "react";

/*
 * 组件注释
 * create by wuqiong
 * creation time 2021/06/29
 * 倒计时
 * */

const Index = (props) => {
  const id = props?.id || "countdown";
  const [countDownTime, setcountDownTime] = useState(null);
  const timer = useRef(null);

  const countDown = (count) => {
    timer.current = setTimeout(() => {
      --count;
      setcountDownTime(count);
      if (count >= 1) {
        sessionStorage.setItem(id, count);
        countDown(count);
      } else {
        sessionStorage.removeItem(id);
        setcountDownTime(null);
      }
    }, 1000);
  };
  useEffect(() => {
    const count = sessionStorage.getItem(id);

    countDown(count);
    return () => {
      sessionStorage.removeItem(id);
      clearInterval(timer.current);
    };
  }, []);
  return [countDownTime, countDown];
};
export default Index;
